A good starting point is always a thorough exam by a vet to rule out obvious physical problems. If the dog only reacts this way when petted, it might be she is anticipating discomfort and flinching away from it. This can become learned behavior so the dog repeats the same action even when she isn't in pain. If she isn't lame and doesn't have an ear infection then this may be the case. If she is lame then the next step would be radiographs.